/*********************************************************************************
 *      Copyright:  (C) 2020 Juan
 *                  All rights reserved.
 *
 *       Filename:  conn_read.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(28/07/20)
 *         Author:  wangruijie <1046299465@qq.com>
 *      ChangeLog:  1, Release initial version on "28/07/20 13:58:56"
 *                 
 ********************************************************************************/
#include "server.h"

/* **********************************************************
 * 函数名：acceptcb
 * 功能：连接客户端
 * 参数：listener，fd，addr，socklen，arg
 * 返回值：
 * **********************************************************/
void acceptcb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *addr, int socklen, void *arg)
{
    EventBase          *base = (EventBase *)arg;
    struct sockaddr_in *sin = (struct sockaddr_in *)addr;
    struct bufferevent *bev;

    printf("connection from %s:%d\n", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));

    /* 设置连接 */
    bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(bev, readcb, NULL, eventcb, NULL);
    bufferevent_enable(bev, EV_READ);
}

/* **************************************************************
 * 函数名：readcb
 * 功能：读取客户端的数据
 * 参数：bev，arg
 * 返回值：
 * **************************************************************/
void readcb(struct bufferevent *bev, void *arg)
{
    char             buf[BUFFER_SIZE];
    char             rbuf[BUFFER_SIZE];
    size_t           n;

    n = bufferevent_read(bev, buf, BUFFER_SIZE - 1);
    buf[n] = '\0';
    unpack_json(buf, rbuf);

    printf("%s\n", buf);
}

/* ************************************************************
 * 函数名：eventcb
 * 功能：出错处理
 * 参数：bev，flag，arg
 * 返回值：
 * ************************************************************/
void eventcb(struct bufferevent *bev, short flag, void *arg)
{
    if(flag & BEV_EVENT_EOF)
    {
        printf("remote peer closed\n");
    }
    else if(flag & BEV_EVENT_ERROR)
    {
        printf("error\n");
    }
    else if (flag & BEV_EVENT_TIMEOUT)
    {
        printf("timeout\n");
    }

    /* 出错了就释放 */
    bufferevent_free(bev);
}
